<!-- 轨迹回放 -->
<template>
  <div class="homePage">
    <split-pane :min-percent="1" :default-percent="treePercent" split="vertical" :hiddenRightBtn="true">
      <template slot="paneL">
        <div class="treeArea">
          <vxe-pulldown ref="xDown2" style="width: 100%;" transfer placement="bottom">
            <template #default>
              <div class="header_search_bar">
                <div class="Toolbar_toolbar_7SMZD Toolbar_toolbar_small_3YfCk">
                  <div class="Toolbar_left_ZORKd Toolbar_left_small_nl0yC" style="width: 100%" >
                    <button type="button" class="Button_btn_nFMrU">
                      <i class="el-icon-search" style="font-size: 16px"></i>
                    </button>
                    <div class="SearchBox_container_3CVB7 SearchBox_border_izcjR" style="width: calc(100% - 71px);" >
                      <div class="SearchBox_clear_1qqjk" v-show="searchValue" @click="clearSearch">
                        <i></i><i class="el-icon-close"></i>
                      </div>
                      <div style="overflow: hidden">
                        <input type="text" placeholder="人员名称" class="SearchBox_input_3l9bT" v-model="searchValue" @focus="$refs.xDown2.showPanel()" />
                      </div>
                    </div>
                    <button type="button" class="Button_btn_nFMrU" style="margin-left: -1px" @click="refreshZTree" >
                      <i class="el-icon-refresh-right" style="font-size: 16px" ></i>
                    </button>
                    <button type="button" class="Button_btn_nFMrU" style="margin-left: -1px; display: none;" >
                      <i class="el-icon-setting" style="font-size: 16px"></i>
                    </button>
                  </div>
                </div>
              </div>
            </template>
            <template #dropdown>
              <div class="my-dropdown2">
                <vxe-list height="240" class="SearchBox_dropdown" :loading="false" :data="searchTableData">
                  <template #default="{ items }">
                    <ul class="ztree" v-for="(item,index) in items" :key="index">
                      <li class="SearchBox_option_item" @click="() => selectNode(item.id)" style="background-color: rgb(255, 255, 255);">
                        <span :class="`button ${item.type == 'Device' ? 'SearchBox_option_item_car' : 'SearchBox_option_item_department'}`">
                        </span>
                        {{item.title}}-{{`(${item.id})`}}
                      </li>
                    </ul>
                  </template>
                </vxe-list>
              </div>
            </template>
          </vxe-pulldown>
          <div class="tree" :style="{height: `calc(100% - ${tableData.length ? '190px' : '153px'})`}">
            <ul id="tree_2020" class="ztree"></ul>
          </div>
          <div class="qury_area" >
            <div style="position: relative; margin-bottom: 5px; height: 32px;" v-if="tableData.length">
              <button type="button" class="Button_btn_nFMrU start_btn" @click="startOrSuspendPlay" >
                <i v-if="!this.intervalTimer" class="el-icon-video-play" title="开始播放" style="font-size: 16px;"></i>
                <i v-if="this.intervalTimer" class="el-icon-video-pause" title="暂停播放" style="font-size: 16px;"></i>
              </button>
              <button type="button" class="Button_btn_nFMrU stop_btn" :style="{cursor: playing ? 'pointer' : 'not-allowed'}" @click="stopPlay" >
                <i class="el-icon-close" title="停止播放" style="font-size: 16px;"></i>
                <div v-if="!this.playing" class="Button_disabled_GJexr" style="left: -1px; top: -1px; width: calc(100% + 2px); height: calc(100% + 2px);"></div>
              </button>
              <vxe-pulldown ref="xDown1" class="action_btn" transfer placement="top">
                <template #default>
                  <button type="button" @click="$refs.xDown1.showPanel()" class="Button_btn_nFMrU action_btn" ><i class="el-icon-setting" style="font-size: 16px;"></i></button>
                </template>
                <template #dropdown>
                  <div class="my-dropdown1">
                    <div class="input_slider_container">
                      <span is-label="" class="input_slider_label">播放速度</span>
                      <div class="slider_container">
                        <el-slider v-model="speed" :min="1" :max="9" :show-tooltip="false" @change="speedChange" ></el-slider>
                      </div>
                    </div>
                    <div class="input_slider_container">
                      <span is-label="" class="input_slider_label">路线宽度</span>
                      <div class="slider_container">
                        <el-slider v-model="polylineWidth" :min="2" :max="6" :show-tooltip="false" @change="polylineWidthChange" ></el-slider>
                      </div>
                    </div>
                    <div class="input_slider_container">
                      <span is-label="" class="input_slider_label">路线颜色</span>
                      <div class="slider_container">
                        <el-color-picker style="position: relative; top: 1.5px;" v-model="polylineColor" @change="polylineColorChange" size="mini"></el-color-picker>
                      </div>
                    </div>
                    <div class="input_slider_container">
                      <span is-label="" class="input_slider_label">路线透明</span>
                      <div class="slider_container">
                        <el-slider v-model="polylineOpacity" :min="0" :step="0.1" :max="1" :show-tooltip="false" @change="polylineOpacityChange" ></el-slider>
                      </div>
                    </div>
                  </div>
                </template>
              </vxe-pulldown>
              
              <div class="play_slider">
                <el-slider v-model="playIndex" :min="0" :format-tooltip="formatTooltip" :max="tableData.length - 1" :step="Math.floor((tableData.length-1)/100) || 1" @change="playIndexChange" ></el-slider>
              </div>
              
            </div>
            <div class="InputDateTime">
              <span is-label="" class="InputDateTime_label" >开始时间</span>
              <div class="InputDateTime_datatime" style="min-width: 82.54px;">
                <vxe-input v-model="startTime" placeholder="选择开始时间" type="datetime" transfer style="width: 100%; font-size: 12px;"></vxe-input>
              </div>
            </div>
            <div class="InputDateTime">
              <span is-label="" class="InputDateTime_label" >结束时间</span>
              <div class="InputDateTime_datatime" style="min-width: 82.54px;">
                <vxe-input v-model="endTime" placeholder="选择结束时间" type="datetime" transfer style="width: 100%; font-size: 12px;"></vxe-input>
              </div>
            </div>

            <el-button size="mini" icon="el-icon-search" @click="queryData" type="primary" class="query_search_btn" >查询</el-button>
          </div>
        </div>
      </template>

      <template slot="paneR">
        <split-pane split="horizontal" :default-percent="65" :min-percent="1">
          <template slot="paneL">
            <div class="map">
              <div
                class="bm-view-big"
                id="mapChart"
                style="width: 100%; height: 100%"
              ></div>
            </div>
          </template>
          <template slot="paneR">
            <div class="tableArea">
              <!-- @current-change="currentChange" @cell-click="currentChange" :keyboard-config="{isArrow: true}" -->
              <vxe-table
                border
                stripe
                highlight-hover-row
                highlight-current-row
                ref="xTable"
                height="auto"
                :auto-resize="true"
                :data="tableData"
                show-overflow
                size="mini"
                resizable
                @current-change="currentChange" 
                :keyboard-config="{isArrow: true}"
                >
                <vxe-table-column type="seq" width="50" title="序号" fixed="left" align="center"></vxe-table-column>
                <vxe-table-column field="dirct" width="50" title="状态" fixed="left" align="center">
                  <template #default="{ row }">
                    <span> 
                      <img :style="`max-width: 20px; max-height: 20px; vertical-align: middle;transform: rotateZ(${row.dirct}deg);`" :src="car7">
                    </span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="createdTime" width="150" title="定位时间" align="center"></vxe-table-column>
                <vxe-table-column field="speed" width="80" title="行驶速度" align="right">
                  <template #default="{ row }">
                    <span>{{ row.speed }}km/h </span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="mile" width="100" title="行驶里程" align="right">
                  <template #default="{ row }">
                    <span>{{ formatMile(row.mile) }}km </span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="addr" title="地理位置" min-width="300" show-overflow></vxe-table-column>
                <vxe-table-column field="empty" title="" show-overflow></vxe-table-column>

                <template #empty>
                  <span >
                  </span>
                </template>
              </vxe-table>
            </div>
          </template>
        </split-pane>
      </template>
    </split-pane>
  </div>
</template>

<script>
import { formatMile } from "_util";
import car7 from '../assets/img/car7.png';
import map_start from '../assets/img/map-start.png';
import map_end from '../assets/img/map-end.png';
import "../utils/zTree/jquery.ztree.core.min.js";
import "../utils/zTree/jquery.ztree.excheck.min.js";

var map, marker, polyline, selectCarID, carNo, openIng;

// 关闭信息窗体
window.closeInfoWindow = function closeInfoWindow(type) {
  if (type == "closeOpen") openIng = false;
  if (window.map) window.map.clearInfoWindow();
  if (type == "closeMarker" && window.clearMarker) window.clearMarker();
};

// 清除 marker
window.clearMarker = function clearMarker() {
  if (marker) {
    marker.setMap(null);
    marker = null;
  }
};

function getDirection(angle) {
  let direction = "";
  if(angle < 90) {
    direction = "东偏北" + (90 - angle) + "°";
  }
  if(angle > 90 && angle < 180) {
    direction = "东偏南" + (angle - 90) + "°";
  }
  if(angle > 180 && angle < 270) {
    direction = "西偏南" + (angle - 180) + "°";
  }
  if(angle > 270) {
    direction = "西偏北" + (angle - 270) + "°";
  }
  return direction;
}

//构建自定义信息窗体
function createInfoWindow(marker, type) {
  var info = document.createElement("div");
  info.className = "custom-info input-card content-window-card";

  // 定义中部内容
  var middle = document.createElement("div");
  middle.className = "info-middle";
  middle.style.backgroundColor = "white";
  let content = `
    <div style="border: 1px solid rgb(64, 150, 209);box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 2px 2px;visibility: visible; box-sizing: border-box; font-size: 12px; text-align: left;">
      <div style="box-sizing: border-box; outline: none; pointer-events: auto; position: relative; z-index: 1; background-color: rgb(255, 255, 255); display: flex; flex-flow: column nowrap; box-sizing: border-box; color: rgb(50, 50, 50); line-height: 1.3em;">
        <div>
          <div style="box-sizing: border-box; height: 30px; color: rgb(255, 255, 255); width: 100%; padding: 5px; background-color: rgb(64, 150, 209);">
            <span style="float: left; line-height: 20px;">
              ${marker?.otherData?.createdTime}
            </span>
            <i onclick="closeInfoWindow('${type || ''}')" class="el-icon-close" style="margin-left: 5px; float: right; font-size: 18px; cursor: pointer;"></i>
          </div>
          <table border="0" cellspacing="0" cellpadding="0" width="100%" style="line-height: 1;">
            <tr>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box; border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
                  人员名称
                </div>
                <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${carNo}" style="box-sizing: border-box;">
                  ${carNo}
                </div>
              </td>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 1px; color: rgb(44, 120, 191); width: 60px;">
                  定位经度
                </div>
                <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${marker?.otherData?.gaoDe_lng}" style="box-sizing: border-box;">
                  ${marker?.otherData?.gaoDe_lng}
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_" style="box-sizing: border-box; border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
                  行驶速度
                </div>
                <div class="GpsHisContent_text_3nB_G" title="${marker?.otherData?.speed} km/h" style="box-sizing: border-box;">
                  ${marker?.otherData?.speed} km/h
                </div>
              </td>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 1px; color: rgb(44, 120, 191); width: 60px;">
                  定位纬度
                </div>
                <div class="GpsHisContent_text_3nB_G" title="${marker?.otherData?.gaoDe_lat}" style="box-sizing: border-box;">
                  ${marker?.otherData?.gaoDe_lat}
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_last_3jTpP" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
                  行驶方向
                </div>
                <div class="GpsHisContent_text_3nB_G GpsHisContent_item_last_3jTpP" title="${getDirection(marker?.otherData?.dirct)}" style="box-sizing: border-box;">
                  ${getDirection(marker?.otherData?.dirct)}
                </div>
              </td>
              <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_last_3jTpP" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 1px; color: rgb(44, 120, 191); width: 60px;">
                  行驶里程
                </div>
                <div class="GpsHisContent_text_3nB_G GpsHisContent_item_last_3jTpP" title="${marker?.otherData?.mile} 千米" style="box-sizing: border-box;">
                  ${formatMile(marker?.otherData?.mile)} 千米
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="6" style="width: 100%; border-bottom: 1px solid rgb(214, 214, 214);"></td>
            </tr>
            <tr>
              <td colspan="6" style="overflow: hidden; white-space: nowrap; width: 100.2%; max-width: 360px; min-width: 360px;">
                <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R GpsHisContent_item_last_3jTpP" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px; height: 72px;">
                  地理位置
                </div>
                <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R GpsHisContent_item_last_3jTpP" title="浙江省宁波市海曙区;永丰西路;银润豪景商务广场-61号楼,银润豪景商务广场-6号楼,银润豪景商务广场-55号楼" style="box-sizing: border-box;margin-bottom: -8px;">
                  <p style="margin:0 0 8px 0">${marker?.otherData?.addr?.split(";")[0]}</p>
                  <p style="margin:0 0 8px 0">${marker?.otherData?.addr?.split(";")[1]}</p>
                  <p style="margin:0 0 8px 0">${marker?.otherData?.addr?.split(";")[2]}</p>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  `;
  middle.innerHTML = content;

  info.appendChild(middle);

  // 定义底部内容
  var bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.style.position = "relative";
  bottom.style.top = "-1px";
  bottom.style.margin = "0 auto";
  var sharp = document.createElement("img");
  sharp.src = "https://webapi.amap.com/images/sharp.png";
  bottom.appendChild(sharp);
  info.appendChild(bottom);
  return info;
};

export default {
  name: "page",
  components: {},
  props: {},
  data() {
    return {
      setting: {
        check: {
          enable: false,
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: 0
          },
        },
        callback: {
          onCheck: this.onTreeCheck,
        },
        view: {
          autoCancelSelected: false,
          selectedMulti: false,
        }
      },
      zNodes: [
        
      ],

      treePercent: 25,

      searchValue: "",

      tableData: [],

      playIndex: 0,
      startTime: "",
      endTime: "",
      intervalTimer: null,
      speed: 5,
      playing: false,
      polylineWidth: 3,
      polylineOpacity: 0.7,
      polylineColor: "#409EFF",
      car7
    };
  },
  // 计算属性
  computed: {
    searchTableData() {
      if (this.searchValue) {
        return this.zNodes.filter(item => item.title.indexOf(this.searchValue) >= 0)
      } else {
        return this.zNodes
      }
    }
  },
  // 方法
  methods: {
    treeToList(tree){
      var queen =[]
      var out =[]
          queen = queen.concat(tree)
      while(queen.length){
        var first = queen.shift()
        if(first.children){
                queen = queen.concat(first.children)
        delete first['children']
        }
        out.push(first)
      }
      return out
    },
    renderTree(callBack) {
      let _this = this;
      let token = localStorage.getItem("pro__Access-Token");
      $.ajax({
        type : "GET",
        url : this.$api.GetDep_Tree,
        beforeSend: function (XMLHttpRequest) {
          XMLHttpRequest.setRequestHeader("Authorization", 'Bearer ' + JSON.parse(token).value);
        },
        data : {},
        success : function(result) {
          let data = [];
          if (result.success) {
            data = _this.treeToList(result.data);
          }
          
          if (data?.length > 0) {
            data.map(item => {
              item.name = item.title;
              item.iconSkin = item.type == 'Org' ? 'pIcon' : 'icon';
              item.isParent = item.type == 'Org';
            })
            _this.zNodes = data;
            $.fn.zTree.init($("#tree_2020"), _this.setting, data);
            callBack && callBack();
          } else {
            _this.$message({
              type: 'error',
              showClose: true,
              message: '未查询到数据！',
              duration: 15000
            });
          }
        },
        //请求失败，包含具体的错误信息
        error : function(e){
          console.log(e.status);
          console.log(e.responseText);
        }
      });
    },
    refreshZTree() {
      $.fn.zTree.destroy();
      this.renderTree(() => {
        this.$message.success('刷新成功！');
        if (selectCarID) {
          let myZTree = $.fn.zTree.getZTreeObj("tree_2020");
          myZTree.getNodeByParam("id", selectCarID).getPath().map(item => {
            myZTree.expandNode(item, true)
          })
          myZTree.selectNode(myZTree.getNodeByParam("id", selectCarID));
        }
      });
    },
    selectNode(id) {
      this.$refs.xDown2.hidePanel().then(() => {
        let myZTree = $.fn.zTree.getZTreeObj("tree_2020");
        myZTree.getNodeByParam("id", id).getPath().map(item => {
          myZTree.expandNode(item, true)
        })
        myZTree.selectNode(myZTree.getNodeByParam("id", id));
      })
    },
    onTreeCheck(event, treeId, treeNode) {
      console.log("🚀 ~ file: Home.vue ~ line 285 ~ onTreeCheck ~ treeNode", treeNode)
    },
    clearSearch() {
      this.searchValue = "";
    },
    inintMap() {
      let _this = this;

      map = new AMap.Map("mapChart", {
        center: [121.54878, 29.85006],
        zoom: 14  ,
        resizeEnable: true,
        // mapStyle: "amap://styles/c6c6d59dafaa271d12b194a5e5b96910",
      });
      window.map = map;
      map.clearMap();
      // 为地图添加工具
      AMap.plugin([
        'AMap.ToolBar',
        'AMap.Scale',
      ], function(){
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        map.addControl(new AMap.ToolBar({
            // 简易缩放模式，默认为 false
            liteStyle: true
        }));
        map.addControl(new AMap.Scale());
      });

      map.on("click", function (e) {
        closeInfoWindow();
      });
    },
    currentChange({row}) {
      // polyline.setOptions({strokeWeight: 10})
      clearMarker();
      closeInfoWindow();
      // 点标记显示内容，HTML要素字符串
      var markerContent =  `<div style="width: 31px; height: 31px;">
          <img style="top: 16px; position: relative; left: -5px; transform: rotateZ(${row.dirct}deg);" src="${car7}">
          <p class="marker_car_num">${carNo}&nbsp;&nbsp;(${row.speed}KM)</p>
        </div>`; 
      marker = new AMap.Marker({
        position: new AMap.LngLat(row.gaoDe_lng, row.gaoDe_lat),
        content: markerContent
      })
      marker.otherData = row;
      marker.setMap(map);
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: "",
        offset: new AMap.Pixel(18, 0),
      });
      infoWindow.setContent(createInfoWindow(marker, 'closeMarker'));
      infoWindow.open(map, marker.getPosition());
      AMap.event.addListener(marker, "click", function () {
        infoWindow.setContent(createInfoWindow(marker, 'closeMarker'));
        infoWindow.open(map, marker.getPosition());
      });
      map.panTo([row.gaoDe_lng, row.gaoDe_lat]);
    },
    queryData() {
      let _this = this;
      let selectCar = $.fn.zTree.getZTreeObj("tree_2020").getSelectedNodes()[0];
      if (!selectCar || selectCar.type !== 'Device') {
        this.$message.error('请先选中设备！');
        return false;
      }
      if (!this.startTime) {
        this.$message.error('请先选择开始时间！');
        return false;
      }
      if (!this.endTime) {
        this.$message.error('请先选择结束时间！');
        return false;
      }
      carNo = selectCar.title;
      selectCarID = selectCar.id;
      map.clearMap();
      this.queryAllGarbagelist();
      this.tableData = [];
      clearInterval(this.intervalTimer);
      this.intervalTimer = null;
      this.playIndex = 0;
      this.playing = false;
      let token = localStorage.getItem("pro__Access-Token");
      
      $.ajax({
        type : "GET",
        url : this.$api.GetData_ByCar,
        beforeSend: function (XMLHttpRequest) {
          XMLHttpRequest.setRequestHeader("Authorization", 'Bearer ' + JSON.parse(token).value);
        },
        data : {
          TmnCode: selectCar.tmnCode,
          searchBeginTime: this.startTime,
          searchEndTime: this.endTime
        },
        success : function(data) {
          if (data.success) {
            // let gpsLocations = data.data.map(item => {
            //   return [item.gaoDe_lng, item.gaoDe_lat]
            // })
            // // GPS 转高德地图坐标
            // AMap.convertFrom(gpsLocations, "gps", function (status, result) {
            //   if (result.info === 'ok') {
            //     data.data.map((item, index) => {
            //       item.gaoDe_lng = result.locations[index].R;
            //       item.gaoDe_lat = result.locations[index].Q;
            //     })
                 _this.tableData = data.data;
                _this.renderPolyline();
            //   }
            // })
          } else {
            _this.$message({
              type: 'error',
              showClose: true,
              message: '未查询到数据！',
              duration: 15000
            });
          }
          
        },
        //请求失败，包含具体的错误信息
        error : function(e){
          console.log(e.status);
          console.log(e.responseText);
        }
      });
    },
    renderPolyline() {
      let datas = this.tableData;
      if (datas.length == 0) {
        return;
      }
      // 绘制轨迹
      polyline = new AMap.Polyline({
        map: map,
        path: datas.map(item => [item.gaoDe_lng, item.gaoDe_lat]),
        showDir:true,
        lineJoin: "round",
        strokeColor: this.polylineColor,  //线颜色
        strokeOpacity: this.polylineOpacity,     //线透明度
        strokeWeight: this.polylineWidth,      //线宽
        strokeStyle: "solid"  //线样式
      });

      // 绘制起点
      let startMarker = new AMap.Marker({
        position: new AMap.LngLat(datas[0].gaoDe_lng, datas[0].gaoDe_lat),
        icon: new AMap.Icon({
          size: new AMap.Size(65, 65), // 图标尺寸
          image: map_start, // Icon的图像
          imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(65, 65), // 根据所设置的大小拉伸或压缩图片
        }),
        offset: new AMap.Pixel(-32, -34),
      });
      startMarker.otherData = datas[0];

      // 绘制终点
      let endMarker = new AMap.Marker({
        position: new AMap.LngLat(datas[datas.length-1].gaoDe_lng, datas[datas.length-1].gaoDe_lat),
        icon: new AMap.Icon({
          size: new AMap.Size(65, 65), // 图标尺寸
          image: map_end, // Icon的图像
          imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(65, 65), // 根据所设置的大小拉伸或压缩图片
        }),
        offset: new AMap.Pixel(-32, -34),
      });
      endMarker.otherData = datas[datas.length-1];

      let startAndEndMarkerList = [startMarker, endMarker];
      // 起点终点绘制信息窗体
      startAndEndMarkerList.map(marker => {
        let infoWindow = new AMap.InfoWindow({
          isCustom: true, //使用自定义窗体
          content: "",
          offset: new AMap.Pixel(15, -15),
        });
        AMap.event.addListener(marker, "click", function () {
          infoWindow.setContent(createInfoWindow(marker));
          infoWindow.open(map, marker.getPosition());
        });
      })
      // 加入地图
      map.add(startAndEndMarkerList)
        
      // 完美视界
      map.setFitView([polyline, ...startAndEndMarkerList]);
    },
    polylineWidthChange() {
      if (polyline) polyline.setOptions({strokeWeight: this.polylineWidth})
    },
    polylineOpacityChange() {
      if (polyline) polyline.setOptions({strokeOpacity: this.polylineOpacity})
    },
    polylineColorChange() {
      if (polyline) polyline.setOptions({strokeColor: this.polylineColor})
    },
    startOrSuspendPlay() {
      this.playing = true;
      if (this.intervalTimer) {
        clearInterval(this.intervalTimer);
        this.intervalTimer = null;
      } else {
        this.intervalTimer = setInterval(() => {
          clearMarker();
          this.$refs.xTable.setCurrentRow(this.tableData[this.playIndex]);
          this.$refs.xTable.scrollToRow(this.tableData[this.playIndex]);
          // 点标记显示内容，HTML要素字符串
          var markerContent = '' +
            '<div class="custom-content-marker">' +
            '   <img style="top: 16px; position: relative; left: -5px; transform: rotateZ('+ this.tableData[this.playIndex].dirct +'deg);" src="'+car7+'">' +
            `   <p class="marker_car_num">${carNo}&nbsp;&nbsp;(${this.tableData[this.playIndex].speed}KM)</p>` +
            '</div>'; 
          marker = new AMap.Marker({
            position: new AMap.LngLat(this.tableData[this.playIndex].gaoDe_lng, this.tableData[this.playIndex].gaoDe_lat),
            content: markerContent
          })
          marker.otherData = this.tableData[this.playIndex];
          let infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: "",
            offset: new AMap.Pixel(18, 0),
          });
          infoWindow.setContent(createInfoWindow(marker, 'closeMarker'));
          marker.setMap(map);
          infoWindow.open(map, marker.getPosition());
          AMap.event.addListener(marker, "click", function () {
            infoWindow.setContent(createInfoWindow(marker, 'closeMarker'));
            infoWindow.open(map, marker.getPosition());
          });
          map.panTo([this.tableData[this.playIndex].gaoDe_lng, this.tableData[this.playIndex].gaoDe_lat]);
          this.playIndex++;
          if (this.playIndex >= this.tableData.length) {
            this.stopPlay()
          }
        }, (1000 - (this.speed * 100)));
      }
    },
    stopPlay() {
      if (this.playing) {
        clearInterval(this.intervalTimer);
        this.intervalTimer = null;
        this.playIndex = 0;
        this.playing = false;
      }
    },
    playIndexChange(value) {
      this.playIndex = value;
      clearMarker();
      this.$refs.xTable.setCurrentRow(this.tableData[this.playIndex]);
      this.$refs.xTable.scrollToRow(this.tableData[this.playIndex]);
      // 点标记显示内容，HTML要素字符串
      var markerContent = '' +
        '<div class="custom-content-marker">' +
        '   <img style="top: 16px; position: relative; left: -5px; transform: rotateZ('+ this.tableData[this.playIndex].dirct +'deg);" src="'+car7+'">' +
        '</div>'; 
      marker = new AMap.Marker({
        position: new AMap.LngLat(this.tableData[this.playIndex].gaoDe_lng, this.tableData[this.playIndex].gaoDe_lat),
        content: markerContent
      })
      marker.setMap(map);
      map.panTo([this.tableData[this.playIndex].gaoDe_lng, this.tableData[this.playIndex].gaoDe_lat]);
    },
    speedChange(value) {
      this.speed = value;
      if (this.playing && this.intervalTimer) {
        clearInterval(this.intervalTimer);
        this.intervalTimer = null;
        this.startOrSuspendPlay();
      }
    },
    formatTooltip(value) {
      return this.tableData[value]?.createTime;
    },
    queryAllGarbagelist() {
      let _this = this;
      // $.ajax({
      //     type : "GET",
      //     url : this.$api.GetAllGarbagelist,
      //     data : { },
      //     success : function(result) {
      //       let data = JSON.parse(result);
      //       //构建自定义信息窗体
      //       function createGarbageInfoWindow(marker, type) {
      //         var info = document.createElement("div");
      //         info.className = "custom-info input-card content-window-card";

      //         // 定义中部内容
      //         var middle = document.createElement("div");
      //         middle.className = "info-middle";
      //         middle.style.backgroundColor = "white";
      //         let content = `
      //           <div style="border: 1px solid rgb(64, 150, 209);box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 2px 2px;visibility: visible; box-sizing: border-box; font-size: 12px; text-align: left;">
      //             <div style="box-sizing: border-box; outline: none; pointer-events: auto; position: relative; z-index: 1; background-color: rgb(255, 255, 255); display: flex; flex-flow: column nowrap; box-sizing: border-box; color: rgb(50, 50, 50); line-height: 1.3em;">
      //               <div>
      //                 <div style="box-sizing: border-box; height: 30px; color: rgb(255, 255, 255); width: 100%; padding: 5px; background-color: rgb(64, 150, 209);">
      //                   <span style="float: left; line-height: 20px;">
      //                     ${marker?.GarbageName}
      //                   </span>
      //                   <i onclick="closeInfoWindow('${type || ''}')" class="el-icon-close" style="margin-left: 5px; float: right; font-size: 18px; cursor: pointer;"></i>
      //                 </div>
      //                 <table border="0" cellspacing="0" cellpadding="0" width="100%" style="line-height: 1;">
      //                   <tr>
      //                     <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
      //                       <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box; border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
      //                         点位名称
      //                       </div>
      //                       <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${marker?.GarbageName}" style="box-sizing: border-box;">
      //                         ${marker?.GarbageName}
      //                       </div>
      //                     </td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="6" style="width: 100%; border-bottom: 1px solid rgb(214, 214, 214);"></td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
      //                       <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box; border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
      //                         督导员
      //                       </div>
      //                       <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${marker?.otherData?.DriverName}" style="box-sizing: border-box;">
      //                         ${marker?.otherData?.DriverName}
      //                       </div>
      //                     </td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="6" style="width: 100%; border-bottom: 1px solid rgb(214, 214, 214);"></td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
      //                       <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box; border-left-color: rgb(214, 214, 214); border-left-width: 0px; color: rgb(44, 120, 191); width: 60px;">
      //                         餐厨垃圾
      //                       </div>
      //                       <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${marker?.otherData?.CanChuBucketNum}桶" style="box-sizing: border-box;">
      //                         ${marker?.otherData?.CanChuBucketNum}桶
      //                       </div>
      //                     </td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="6" style="width: 100%; border-bottom: 1px solid rgb(214, 214, 214);"></td>
      //                   </tr>
      //                   <tr>
      //                     <td colspan="3" style="overflow: hidden; white-space: nowrap; width: 50.1%; max-width: 200px; min-width: 183px;">
      //                       <div is-label="true" class="GpsHisContent_label_2Qgp_ GpsHisContent_item_first_1e92R" style="box-sizing: border-box;border-left-color: rgb(214, 214, 214); border-left-width: 1px; color: rgb(44, 120, 191); width: 60px;">
      //                         其他垃圾
      //                       </div>
      //                       <div class="GpsHisContent_text_3nB_G GpsHisContent_item_first_1e92R" title="${marker?.otherData?.QiTBucketNum}桶" style="box-sizing: border-box;">
      //                         ${marker?.otherData?.QiTBucketNum}桶
      //                       </div>
      //                     </td>
      //                   </tr>
                       
      //                 </table>
      //               </div>
      //             </div>
      //           </div>
      //         `;
      //         middle.innerHTML = content;

      //         info.appendChild(middle);

      //         // 定义底部内容
      //         var bottom = document.createElement("div");
      //         bottom.className = "info-bottom";
      //         bottom.style.position = "relative";
      //         bottom.style.top = "-1px";
      //         bottom.style.margin = "0 auto";
      //         var sharp = document.createElement("img");
      //         sharp.src = "https://webapi.amap.com/images/sharp.png";
      //         bottom.appendChild(sharp);
      //         info.appendChild(bottom);
      //         return info;
      //       };

      //       let garbageInfoWindow = new AMap.InfoWindow({
      //         isCustom: true, //使用自定义窗体
      //         content: "",
      //         offset: new AMap.Pixel(18, 0),
      //       });

      //       if (data.code == 0 && data?.data?.length > 0) {
      //         data.data.map(item => {
      //           var marker = new AMap.Marker({
      //             position: new AMap.LngLat(item.Longitude, item.Latitude),
      //             icon: new AMap.Icon({
      //               image: _this.$api.doMain + item.IconUrl, // Icon的图像
      //               imageOffset: new AMap.Pixel(5, 10), // 图像相对展示区域的偏移量，适于雪碧图等
      //               imageSize: new AMap.Size(15, 20), // 根据所设置的大小拉伸或压缩图片
      //             }),
      //             title: item.GarbageName,
      //           });
      //           // 公厕名称
      //           marker.GarbageName = item.GarbageName;
      //           marker.otherData = item;
      //           map.add(marker);
      //           AMap.event.addListener(marker, "click", function() {
      //             garbageInfoWindow.setContent(createGarbageInfoWindow(marker));
      //             garbageInfoWindow.open(map, marker.getPosition());
      //           })
      //         })
      //       }
      //     }
      // })

    },
    formatMile: formatMile
  },
  // 观察属性
  watch: {},
  beforeRouteEnter(to, from, next) {
    next(/* vm => {} */);
  },
  beforeRouteUpdate(to, from, next) {
    next();
  },
  beforeRouteLeave(to, from, next) {
    next();
  },
  beforeCreate() {
    // 生命周期钩子：组件实例刚被创建，组件属性计算之前，如 data 属性等
  },
  created() {
    // 生命周期钩子：组件实例创建完成，属性已绑定，但 DOM 还未生成，el 属性还不存在
  },
  beforeMount() {
    // 生命周期钩子：模板编译/挂载之前
  },
  mounted() {
    // 生命周期钩子：模板编译、挂载之后（此时不保证已在 document 中）
    this.renderTree();
    this.inintMap();
    this.queryAllGarbagelist();
    this.startTime = new Date().Format("yyyy-MM-dd") + ' 00:00:00';
    this.endTime = new Date().Format("yyyy-MM-dd") + ' 23:59:59';

    // 初始化左侧树的宽度为250px max 95%宽度
    this.treePercent = Math.ceil((250/$(document).width())*100) > 95 ? 95 : Math.ceil((250/$(document).width())*100);

  },
  beforeUpate() {
    // 生命周期钩子：组件更新之前
  },
  updated() {
    // 生命周期钩子：组件更新之后
  },
  activated() {
    // 生命周期钩子：keep-alive 组件激活时调用
  },
  deactivated() {
    // 生命周期钩子：keep-alive 组件停用时调用
  },
  beforeDestroy() {
    // 生命周期钩子：实例销毁前调用
  },
  destroyed() {
    // 生命周期钩子：实例销毁后调用
  },
  errorCaptured(err, vm, info) {
    // 生命周期钩子：当捕获一个来自子孙组件的错误时被调用。此钩子会收到三个参数：错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。
    console.log(err, vm, info);
  },
};
</script>
<style lang="less" scoped>

.homePage {
  height: calc(~"100% - 20px");
  width: calc(~"100% - 20px");
  background-color: rgb(232, 234, 237);
  padding: 10px;
  .treeArea {
    width: calc(~"100% - 7px");
    height: calc(~"100% - 2px");
    overflow: auto;
    border-style: solid;
    border-width: 1px;
    border-color: rgb(174, 186, 197);
    background: #e8eaed;
    .Toolbar_toolbar_7SMZD {
      background-color: rgb(232, 234, 237);
      border-width: 0px 0px 1px;
      border-top-style: initial;
      border-right-style: initial;
      border-bottom-style: solid;
      border-left-style: initial;
      border-color: rgb(214, 214, 214);
      border-image: initial;
      .Toolbar_left_ZORKd {
        .Button_btn_nFMrU {
          border-color: rgb(214, 214, 214);
          background-color: rgb(232, 234, 237);
          height: 32px;
          padding: 2px 0px 0px;
          border-width: 1px;
          cursor: pointer;
          border-radius: 0px;
          width: 32px;
          &:hover {
            background-color: rgb(255, 255, 255);
            color: rgb(64, 150, 209);
          }
        }
        .SearchBox_container_3CVB7 {
          height: 30px;
          border-color: rgb(214, 214, 214);
          margin-left: -1px;
          width: calc(100% - 103px);
        }
      }
    }
    .tree {
      overflow: auto;
      background: #fff;
      // height: calc(~"100% - 190px");
    }
    .qury_area {
      width: 100%;
      border-top: 1px solid rgb(174, 186, 197);
      padding: 5px;
      position: relative;
      box-sizing: border-box !important;
      font-size: 12px;
      background: #fff;
      * {
        box-sizing: border-box !important;
      }
      .start_btn {
        background-color: rgb(255, 255, 255);
        border-color: rgb(174, 186, 197);
        height: 32px;
        padding: 0px;
        border-width: 1px;
        cursor: pointer;
        border-radius: 0px;
        position: absolute;
        width: 32px;
        left: 0px;
        bottom: 0px;
      }
      .stop_btn {
        background-color: rgb(255, 255, 255);
        border-color: rgb(174, 186, 197);
        height: 32px;
        padding: 0px;
        border-width: 1px;
        border-radius: 0px;
        position: absolute;
        left: 31px;
        bottom: 0px;
        width: 32px;
        color: rgb(112, 112, 112);
      }
      .action_btn {
        background-color: rgb(255, 255, 255);
        border-color: rgb(174, 186, 197);
        height: 32px;
        padding: 0px;
        border-width: 1px;
        cursor: pointer;
        border-radius: 0px;
        position: absolute;
        right: 0px;
        bottom: 0px;
        width: 32px;
      }
      .Button_disabled_GJexr {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        background-color: hsla(0,0%,92.2%,.6);
        opacity: .6;
        filter: alpha(opacity=60);
        cursor: not-allowed;
      }
      .play_slider {
        position: absolute;
        left: 62px;
        bottom: 0px;
        right: 31px;
        border: 1px solid rgb(174, 186, 197);
        height: 32px;
        background-color: rgb(255, 255, 255);
        padding: 0 15px;
        /deep/.el-slider__runway {
          margin: 12px 0;
          .el-slider__button-wrapper {
            height: 25px;
            width: 25px;
            top: -10px;
            .el-slider__button {
              width: 8px;
              height: 8px;
            }
          }
        }
      }
      .InputDateTime {
        outline: none;
        display: inline-block;
        white-space: nowrap;
        background-color: #fff;
        position: relative;
        user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        -moz-user-select: none;
        border-style: solid;
        border-width: 1px;
        height: 32px;
        border-color: rgb(174, 186, 197);;
        width: 100%;
        margin-top: -1px;
        &:hover {
          border-color: rgb(64, 150, 209);
          z-index: 2549;
        }
        .InputDateTime_label {
          font-size: 12px;
          float: left;
          padding: 0 6px;
          border-right-style: solid;
          border-right-width: 0;
          white-space: nowrap;
          height: 100%;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
          border-right-color: rgb(214, 214, 214);
          background-color: rgb(232, 234, 237);
          width: 60px;
        }
        .InputDateTime_datatime {
          font-size: 13px;
          white-space: nowrap;
          overflow: hidden;
          cursor: pointer;
          height: 100%;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
        }
        /deep/.vxe-input--inner {
          border: none;
        }
        /deep/.vxe-input--date-picker-icon {
          font-size: 16px;
          transform: translate(-11px,-50%);
        }
        /deep/.vxe-input:not(.is--disabled).is--active .vxe-input--inner {
          border: none;
        }
      }
      .query_search_btn {
        margin-top: 5px;
        width: 100%;
        border-radius: 0;
        height: 32px;
        /deep/i {
          font-size: 16px;
        }
        /deep/span {
          position: relative;
          top: -2px;
        }
      }
    }
  }
  .map {
    width: calc(~"100% - 7px");
    height: calc(~"100% - 7px");
    margin-left: 5px;
    background: #fff;
     border-style: solid;
    border-width: 1px;
    border-color: rgb(174, 186, 197);
  }
  .tableArea {
    width: calc(~"100% - 7px");
    height: calc(~"100% - 7px");
    margin-left: 5px;
    margin-top: 5px;
    background: #fff;
     border-style: solid;
    border-width: 1px;
    border-color: rgb(174, 186, 197);
  }
  .line_btn {
    z-index: 999;
  }
}
</style>